//
//  ComposeViewController.swift
//  WeiBo test
//
//  Created by Aquarius_wing on 16/5/12.
//  Copyright © 2016年 Wing. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    
    //监听方法
    @objc private func close(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send(){
        let urlString="2/statuses/update.json"
        guard let token = UserAccountViewModel().token else{
            SVProgressHUD.showErrorWithStatus("未登录!")
            return
        }
        let parameters=["access_token":token,"status":textView.text]
        NetWorkTools.sharedTools.requestJsonDict(HTTPMethod.POST, urlString: urlString, parameters: parameters) { (result, error) in
            if error != nil{
                print("send error!",error)
                SVProgressHUD.showErrorWithStatus(APPERRORTIP)
                return
            }
            //得到数据
            print("result",result)
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            self.close()
            
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor=UIColor.whiteColor()
        
        setupUI()
    }
    
    private func setupUI(){
        //设置导航条
        setNavBar()
        //设置输入文本
        setupTextView()
        //设置底部工具栏
        setupToolBar()
        //注册通知
        registerNotification()
    }    
    
    private func registerNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillChange), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    @objc private func keyboardWillChange(n:NSNotification){
        print(n)
        //获取动画时间
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //修改toolBar约束
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(-SCREENSIZE.height+rect.origin.y)
        }
        UIView.animateWithDuration(duration) { 
            //强制刷新
            self.view.layoutIfNeeded()
        }
    }

    private lazy var textView:UITextView={
        let tv=UITextView()
        tv.delegate=self
        tv.font=UIFont.systemFontOfSize(18)
        tv.textColor=UIColor.darkGrayColor()
        //设置键盘消失模式
        tv.keyboardDismissMode = .OnDrag
        //弹簧属性设置
        tv.alwaysBounceVertical=true
        return tv
    }()
    //工具条
    private lazy var toolBar:UIToolbar=UIToolbar()
    private lazy var placeHolderLabel:UILabel=UILabel(title: "分享新鲜事...", size: 18, color: UIColor.lightGrayColor())
}

//MARK: 协议方法
extension ComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden=textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled=textView.hasText()
    }
}

//MARK: 设置UI
extension ComposeViewController{
    private func setupToolBar(){
        view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(40)
        }
        //设置Toolbar的按钮 以及点击事件
        var items=[UIBarButtonItem]()
        
        //添加 UIBarButtonItem
        let itemSettings=[["imageName":"compose_toolbar_picture"],["imageName":"compose_mentionbutton_background"],["imageName":"compose_trendbutton_background"],["imageName":"compose_emoticonbutton_background"],["imageName":"compose_add_background"]]
        for dict in itemSettings{
//            let btn = UIButton(type: .Custom)
//            btn.setImage(UIImage(named: dict["imageName"]!), forState: .Normal)
//            btn.setImage(UIImage(named: dict["imageName"]!+"_highlighted"), forState: .Highlighted)
//            let item = UIBarButtonItem(customView: btn)
//            btn.sizeToFit()
            let item = UIBarButtonItem(imageName: dict["imageName"]!)
            items.append(item)
            //实例化一个弹簧
            let space=UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        toolBar.items=items
    }
    
    private func setupTextView(){
        view.addSubview(textView)
        textView.becomeFirstResponder()
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height/3)
        }
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    private func setNavBar(){
        self.navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(ComposeViewController.close))
        self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "发布", style: .Plain, target: self, action: #selector(ComposeViewController.send))
        self.navigationItem.rightBarButtonItem?.enabled=false
        let titleView=UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //        titleView.backgroundColor=UIColor.lightGrayColor()
        navigationItem.titleView=titleView
        
        let titleLabel=UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        var name=""
        if let account = UserAccountViewModel().account {
            name=account.name!
        }
        let nameLabel=UILabel(title: name, size: 14, color: UIColor.lightGrayColor())
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(titleView)
            make.top.equalTo(titleView)
            
        }
        nameLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(titleView)
            make.bottom.equalTo(titleView)
            
        }
    }
}
